﻿using Newtonsoft.Json;
using OConf.NetCore.Common;
using OConf.NetCore.Model;
using OConf.NetCore.Options;

namespace OConf.NetCore.Static
{
    /// <summary>
    /// 静态类、静态方法
    /// </summary>
    public static class ConfigCommon
    {
        /// <summary>
        /// 保存json文件
        /// </summary>
        /// <param name="dicPath"></param>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private static bool SaveJsonFile(string dicPath, string fileName, string content)
        {
            Directory.CreateDirectory(dicPath);
            return FileCore.SaveFile(Path.Combine(dicPath, $"{fileName}.json"), content);
        }

        /// <summary>
        /// 保存项目配置信息和配置信息
        /// </summary>
        /// <param name="configInfo"></param>
        internal static void SaveConfigInfo(BackProgramConfigInfo configInfo)
        {
            if (configInfo == null || configInfo.NameSpaces == null || configInfo.NameSpaces.Count <= 0)
            {
                return;
            }

            //过滤不需要加载的空间信息
            configInfo.NameSpaces = configInfo.NameSpaces.Where(w => ConfigNameSpaceOptions.GetNameSpace().Contains(w.NameSpace)).ToList();

            #region 保存项目配置信息
            ProjectConfigModel projectConfig = new ProjectConfigModel()
            {
                LastPublishTime = configInfo.LastPublishTime,
            };

            SaveJsonFile(Cache.saveDicPath, Cache.projectConfigFileName, JsonConvert.SerializeObject(projectConfig));
            #endregion

            #region 保存配置信息
            foreach (var item in configInfo.NameSpaces)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (var config in item.ConfigInfos)
                {
                    dic.Add(config.Key, config.Value);
                }
                SaveJsonFile(Cache.saveDicPath, item.NameSpace, JsonConvert.SerializeObject(dic));
            }
            #endregion
        }
    }
}
